package com.xmg.p2p.base.controller;

import com.xmg.p2p.base.domain.RealAuth;
import com.xmg.p2p.base.domain.Userinfo;
import com.xmg.p2p.base.service.IRealAuthService;
import com.xmg.p2p.base.service.IUserinfoService;
import com.xmg.p2p.base.util.JSONResult;
import com.xmg.p2p.base.util.RequireLogin;
import com.xmg.p2p.base.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;

@Controller
public class RealAuthController {
    @Autowired
    private IRealAuthService realAuthService;
    @Autowired
    private IUserinfoService userinfoService;
    @Autowired
    private ServletContext servletContext;

    /**
     * 获取当前用户信息,根据是否实名认证返回对应视图
     * 1.已认证，返回结果视图，并设置auditing为false；
     * 2.未认证，realAuthId不为空，返回结果视图，设置auditing为true；
     * 3.未认证，realAuthId不为空，返回填写审核视图。
     * @param model
     * @return
     */
    @RequireLogin
    @RequestMapping("realAuth")
    public String realAuth(Model model){
        Userinfo current = userinfoService.getCurrent();
        if(current.getIsRealAuth()){
            model.addAttribute("realAuth",realAuthService.get(current.getRealAuthId()));
            model.addAttribute("auditing",false);
            return "realAuth_result";
        }else {
            if(current.getRealAuthId()==null){
                return "realAuth";
            }else {
                model.addAttribute("auditing",true);
                return "realAuth_result";
            }
        }
    }
    @ResponseBody
    @RequestMapping("realAuthUpload")
    public String realAuthUpload(MultipartFile file){
        String fileName = UploadUtil.upload(file, servletContext.getRealPath("/upload"));
        return "/upload/"+fileName;
    }
    @RequireLogin
    @RequestMapping("realAuth_save")
    @ResponseBody
    public JSONResult apply(RealAuth realAuth){
        realAuthService.apply(realAuth);
        return new JSONResult();
    }
}
